
import monitor from '../frame/monitor';

class Danmaku {

	/** @type {string} uuid */
	assetId;
	/** @type {number} B 站的用户 id */
	uid;
	/** @type {function (any): void} */
	onDanmuReceived;
	/** @type {function (any): void} */
	onEnterReceived;
	/** @type {function (any): void} */
	onGiftReceived;

	/**
	 * @param {number} roomId 
	 */
	constructor(roomId) {
		this.roomId = roomId;
		this.baseTime = 0;
	}

	createSource() {
		return fetch(`/aurora/asset/danmaku/create?roomId=${this.roomId}`)
			.then(d => d.json())
			.then(d => {
				this.assetId = d.data.id;
				this.uid = d.data.uid;
				return this.id;
			});
	}

	openSource() {
		return fetch(`/aurora/asset/danmaku/start/${this.assetId}`)
			.then(d => {
				this.baseTime = Date.now();
				// attach asset
				monitor.sendAttachAssetEvent(this.assetId, null);
			});
	}

	renewLife() {
		this.baseTime = Date.now();
		fetch(`/aurora/asset/danmaku/start/${this.assetId}`)
	}

	filterAssetTick(assetId, data) {
		if (assetId != this.assetId) {
			return false;
		}
		// data 是列表形式的
		for (var o in data) {
			if (data[o].t == 'DANMU') {
				this.onDanmuReceived ? this.onDanmuReceived(data[o]) : o;
			} else if (data[o].t == 'ENTER') {
				this.onEnterReceived ? this.onEnterReceived(data[o]) : o;
			} else if (data[o].t == 'GIFT') {
				this.onGiftReceived ? this.onGiftReceived(data[o]) : o;
			}
			// else
		}

		// 3 小时 = 10800000 ms, 每过三小时都需要让 danmaku 续一次命, 别让它回收了.
		const renewThreshold = Date.now() - 10800000;
		if (renewThreshold > this.baseTime) {
			this.renewLife();
		}

		return true;
	}
}

export default Danmaku;
